<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单数据展示</title>
    <link rel="stylesheet" href="css/style.css">
    <style>
        :root {
            --primary: #2c6ecb;
            --primary-light: #4a89dc;
            --primary-dark: #1a56b3;
            --secondary: #f5a623;
            --success: #27ae60;
            --danger: #e74c3c;
            --gray-light: #f5f7fa;
            --gray: #e4e7ed;
            --gray-dark: #909399;
            --text: #303133;
            --text-light: #606266;
            --border-radius: 6px;
            --shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            line-height: 1.6;
            color: var(--text);
            background-color: #f8f9fa;
        }

        .header {
            background-color: var(--primary);
            color: white;
            padding: 1.5rem;
            text-align: center;
            border-radius: var(--border-radius);
            margin-bottom: 20px;
            box-shadow: var(--shadow);
        }

        .header h1 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 500;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .dashboard-layout {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .tab-container {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .tab-button {
            padding: 12px 24px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            cursor: pointer;
            border-radius: 6px 6px 0 0;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .tab-button:hover {
            background-color: #e9ecef;
        }

        .tab-button.active {
            background-color: var(--primary-color);
            color: white;
        }

        .tab-content {
            display: none;
            padding: 24px;
            border: none;
            border-radius: 6px;
            background-color: white;
            box-shadow: var(--shadow);
        }

        .tab-content.active {
            display: block;
        }

        .search-container {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .form-section {
            background-color: white;
            border-radius: var(--border-radius);
            padding: 16px;
            margin-bottom: 20px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    }

    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
        background-color: white;
        border-radius: var(--border-radius);
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    }

    th, td {
        padding: 12px 15px;
        text-align: left;
    }

    th {
        background-color: var(--gray-light);
        color: var(--text-light);
        font-weight: 500;
        position: sticky;
        top: 0;
        z-index: 1;
    }

    tr:hover {
        background-color: rgba(44, 110, 203, 0.03);
    }

    tr:nth-child(even) {
        background-color: var(--gray-light);
    }

    .detail-button {
        background-color: #2196F3;
        color: white;
        padding: 5px 10px;
        border: none;
        cursor: pointer;
    }

    .pass-button {
        background-color: #4CAF50;
        color: white;
        padding: 5px 10px;
        border: none;
        cursor: pointer;
    }

    .modal {
        display: none;
        position: fixed;
            z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
        background-color: #fefefe;
            margin: 5% auto;
            padding: 0;
            border-radius: 8px;
        width: 80%;
            max-width: 800px;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            animation: slideIn 0.3s ease-out;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #eee;
            background: #f8f9fa;
            border-radius: 8px 8px 0 0;
        }

        .modal-title {
            margin: 0;
            color: var(--primary-dark);
            font-size: 1.5rem;
            font-weight: 600;
    }

    .close {
        color: #aaa;
        font-size: 28px;
        font-weight: bold;
            cursor: pointer;
            transition: color 0.3s ease;
        }

        .close:hover {
            color: #000;
        }

        .modal-body {
            padding: 20px;
            flex: 1;
            overflow-y: auto;
            max-height: 60vh;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .exercises-section {
            margin-top: 20px;
        }

        .exercises-section h3 {
            color: var(--primary-dark);
            margin-bottom: 15px;
            font-size: 1.2rem;
            font-weight: 600;
        }

    .table-container {  
            overflow-x: auto;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .exercises-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }

        .exercises-table th,
        .exercises-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .exercises-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: var(--text);
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            min-width: 100px;
            justify-content: center;
            white-space: nowrap;
        }

        .btn:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .btn-icon {
            font-size: 12px;
        }

        .btn-view {
            background: var(--primary-color);
        }

        .btn-view:hover {
            background: var(--primary-dark);
        }

        .btn-mark-read {
            background: var(--secondary);
        }

        .btn-mark-read:hover {
            background: #e67e22;
        }

        .btn-resume {
            background: var(--success);
        }

        .btn-resume:hover {
            background: #229954;
        }

        .btn-detail {
            background: var(--primary-color);
        }

        .btn-detail:hover {
            background: var(--primary-dark);
        }

        .btn-pass {
            background: #28a745 !important;
            color: white !important;
        }

        .btn-pass:hover {
            background: #218838 !important;
        }

        .btn-pass:disabled {
            background: #28a745 !important;
            opacity: 0.8;
            cursor: not-allowed;
        }

        .btn-mail {
            background: var(--primary-color);
        }

        .btn-mail:hover {
            background: var(--primary-dark);
        }

        .notification-actions {
            display: flex;
            gap: 8px;
            margin-top: 10px;
            flex-wrap: wrap;
            align-items: center;
        }

        .notification-actions .btn {
            flex: 0 0 auto;
            min-width: 100px;
            height: 36px;
        }

        /* 确保通知中心的所有按钮大小一致 */
        .notification-actions .btn-resume,
        .notification-actions .btn-pass,
        .notification-actions .btn-mail {
            width: 100px !important;
            height: 36px !important;
            padding: 8px 12px !important;
            font-size: 14px !important;
        }

        .table-actions {
            display: flex;
            gap: 8px;
            justify-content: center;
            align-items: center;
        }

        /* 邮件编辑区域样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text);
        }

        .form-group input[type="email"],
        .form-group input[type="text"],
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }

        .form-group input[type="email"]:focus,
        .form-group input[type="text"]:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(44, 110, 203, 0.1);
        }

        .form-group textarea {
            min-height: 200px;
            resize: vertical;
        }

        /* 邮件模态框样式优化 */
        .modal-content {
            max-width: 600px;
        }

        .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }



        /* 简历模态框样式优化 */
        #resumeModal .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        #resumeModal .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
        }

        #resumeModal .modal-title {
            color: white;
        }

        #resumeModal .close {
            color: white;
        }

        #resumeModal .close:hover {
            color: #f0f0f0;
        }

        /* PDF iframe 样式 */
        #resumeContent iframe {
            border: none;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* 详细信息模态框样式 */
        #detailModal .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        #detailModal .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
        }

        #detailModal .modal-title {
            color: white;
        }

        #detailModal .close {
            color: white;
        }

        #detailModal .close:hover {
            color: #f0f0f0;
        }

        /* 评价模态框样式 */
        #evaluationModal .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        #evaluationModal .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
        }

        #evaluationModal .modal-title {
            color: white;
        }

        #evaluationModal .close {
            color: white;
        }

        #evaluationModal .close:hover {
            color: #f0f0f0;
        }

        /* 简历模态框样式 */
        #resumeModal .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        #resumeModal .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
        }

        #resumeModal .modal-title {
            color: white;
        }

        #resumeModal .close {
            color: white;
        }

        #resumeModal .close:hover {
            color: #f0f0f0;
        }

        /* 评价表单样式 */
        #detailEvaluationForm .form-group,
        #resumeEvaluationForm .form-group {
            margin-bottom: 15px;
        }

        #detailEvaluationForm textarea,
        #resumeEvaluationForm textarea {
            background: #fafafa;
            border: 1px solid #e0e0e0;
            transition: border-color 0.3s ease;
        }

        #detailEvaluationForm textarea:focus,
        #resumeEvaluationForm textarea:focus {
            background: white;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
        }

        /* 按钮统一样式 */
        .btn {
            min-width: 100px !important;
            height: 36px !important;
            padding: 8px 12px !important;
            font-size: 14px !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            white-space: nowrap !important;
            border-radius: 4px !important;
            border: 1px solid transparent !important;
            cursor: pointer !important;
            transition: all 0.3s ease !important;
            text-decoration: none !important;
            box-sizing: border-box !important;
        }

        .btn:hover {
            opacity: 0.8 !important;
            transform: translateY(-1px) !important;
        }

        .btn:active {
            transform: translateY(0) !important;
        }

        /* 按钮颜色样式 */
        .btn-detail {
            background: #007bff !important;
            color: white !important;
        }

        .btn-detail:hover {
            background: #0056b3 !important;
        }

        .btn-mail {
            background: #28a745 !important;
            color: white !important;
        }

        .btn-mail:hover {
            background: #1e7e34 !important;
        }

        .btn-resume {
            background: #ffc107 !important;
            color: #212529 !important;
        }

        .btn-resume:hover {
            background: #e0a800 !important;
        }

        .btn-evaluation {
            background: #6c757d !important;
            color: white !important;
        }

        .btn-evaluation:hover {
            background: #5a6268 !important;
        }

        /* 查看评价按钮特殊颜色 */
        .btn-evaluation[onclick*="viewEvaluation"] {
            background: #17a2b8 !important;
        }

        .btn-evaluation[onclick*="viewEvaluation"]:hover {
            background: #138496 !important;
        }

        /* 通知中心按钮样式 */
        .btn-view {
            background: #007bff !important;
            color: white !important;
        }

        .btn-view:hover {
            background: #0056b3 !important;
        }

        .btn-mark-read {
            background: #6c757d !important;
            color: white !important;
        }

        .btn-mark-read:hover {
            background: #5a6268 !important;
        }

        .btn-pass {
            background: #28a745 !important;
            color: white !important;
        }

        .btn-pass:hover {
            background: #1e7e34 !important;
        }

        /* 确保表格中的按钮对齐 */
        .accounting-table td {
            vertical-align: middle !important;
        }

        .accounting-table .btn {
            margin: 2px !important;
        }


</style>
</head>
<body>


    <header class="header">
        <h1>上海莱升信息科技有限公司面试系统</h1>
        <p class="header-description">后台管理系统 - 面试数据管理与通知中心</p>
    </header>
    
    <div class="dashboard-layout">
    <div class="tab-container">
            <button class="tab-button" onclick="showTab('notifications')">
                <span class="tab-icon">🔔</span>
                通知中心
                <span class="notification-badge" id="notificationBadge" style="display: none;">0</span>
            </button>
            <button class="tab-button active" onclick="showTab('accounting')">
                <span class="tab-icon">📊</span>
                面试数据
            </button>
</div>

        <!-- 通知中心标签页 -->
        <div id="notifications" class="tab-content">
            <!-- 通知搜索和操作区域 -->
            <div class="notification-search-container" style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                    <label style="margin-right: 10px; font-weight: 500; color: #333;">时间搜索：</label>
                    <input type="date" id="notificationSearchDate" style="padding: 8px; width: 150px; border: 1px solid #ddd; border-radius: 4px;">
                    <button onclick="searchNotifications()" style="padding: 8px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">搜索</button>
                    <button onclick="clearNotificationSearch()" style="padding: 8px 15px; background-color: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;">清空</button>
                    <button onclick="markAllAsRead()" style="padding: 8px 15px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer;">全部已读</button>
                    <button onclick="markSelectedAsRead()" style="padding: 8px 15px; background-color: #17a2b8; color: white; border: none; border-radius: 4px; cursor: pointer;">批量已读</button>
                    <span id="notificationCount" style="margin-left: auto; font-weight: 500; color: #666; white-space: nowrap;">共 0 条通知</span>
                </div>
            </div>
            
            <div class="notification-container">
                <div class="notification-header">
                    <span class="notification-title">面试通知</span>
                </div>
                <div class="notification-list" id="notificationList">
                    <!-- 通知列表将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>

        <!-- 面试数据标签页 -->
        <div id="accounting" class="tab-content active">
            <div class="search-container" style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px;">
                <label style="margin-right: 10px; font-weight: 500; color: #333;">搜索条件：</label>
                <input type="text" id="searchName" placeholder="输入姓名模糊搜索..." style="padding: 8px; width: 200px; border: 1px solid #ddd; border-radius: 4px;" onkeypress="handleKeyPress(event)">
                <input type="date" id="searchDate" style="padding: 8px; width: 150px; margin-left: 10px; border: 1px solid #ddd; border-radius: 4px;">
                <button onclick="searchAccountingData()" style="padding: 8px 15px; margin-left: 10px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">搜索</button>
                <button onclick="clearSearch()" style="padding: 8px 15px; margin-left: 10px; background-color: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;">清空</button>
            </div>
    <table id="accountingTable">
        <thead>
        <tr>
            <th>姓名</th>
            <th>性别</th>
            <th>手机号</th>
            <th>申请职位</th>
            <th>面试时间</th>
            <th style="text-align: center;">面试状态</th>
            <th style="text-align: center;">简历</th>
            <th style="text-align: center;">面试评价</th>
            <th style="text-align: center;">操作</th>
            <th style="text-align: center;">发送邮件</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
    <!-- 添加分页控件 -->
    <div class="pagination" style="margin-top: 15px; text-align: center;">
        <button id="prevPage" onclick="changePage(-1)" style="padding: 8px 15px; margin-right: 10px;">上一页</button>
        <span id="pageInfo">第 1 页 / 共 0 页</span>
        <button id="nextPage" onclick="changePage(1)" style="padding: 8px 15px; margin-left: 10px;">下一页</button>
            </div>
    </div>
</div>

<!-- 详细信息模态框 -->
<div id="detailModal" class="modal">
    <div class="modal-content" style="max-width: 95%; width: 1200px; max-height: 90vh;">
        <div class="modal-header">
            <h2 class="modal-title">📋 详细信息</h2>
            <span class="close" onclick="closeDetailModal()">&times;</span>
        </div>
        <div class="modal-body" style="padding: 20px; display: flex; gap: 20px; height: calc(90vh - 120px);">
            <!-- 左侧：用户详细信息 -->
            <div style="flex: 1; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow-y: auto;">
                <div style="padding: 20px;">
                    <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px; border-bottom: 2px solid #667eea; padding-bottom: 8px;">
                        👤 用户详细信息
                    </h3>
                    <div id="userInfo"></div>
                    <div class="exercises-section" style="margin-top: 20px;">
                        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px; border-bottom: 2px solid #667eea; padding-bottom: 8px;">
                            💻 开发测试题答案
                        </h3>
                        <div class="table-container">
                            <table id="exercisesTable" class="exercises-table">
                                <thead>
                                    <tr>
                                        <th>问题</th>
                                        <th>答案</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：面试评价 -->
            <div style="flex: 1; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); display: flex; flex-direction: column;">
                <div style="padding: 20px; border-bottom: 1px solid #eee;">
                    <h3 style="margin: 0; color: #333; font-size: 16px; border-bottom: 2px solid #667eea; padding-bottom: 8px;">
                        📝 面试评价
                    </h3>
                </div>
                <div style="flex: 1; padding: 20px; overflow-y: auto;">
                    <form id="detailEvaluationForm" onsubmit="saveDetailEvaluation(event)">
                        <input type="hidden" id="detailEvaluationAccountingId" name="accountingId">
                        <div class="form-group">
                            <label for="detailEvaluationContent" style="font-size: 14px; font-weight: 500; margin-bottom: 8px; display: block;">评价内容：</label>
                            <textarea id="detailEvaluationContent" name="content" rows="12" required 
                                      placeholder="请记录对面试者的评价、印象、技术能力、沟通能力等..."
                                      style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.4; resize: none; border: 1px solid #ddd; border-radius: 4px; padding: 8px; width: 100%; box-sizing: border-box; font-size: 13px;"
                                      oninput="updateDetailEvaluationWordCount()"></textarea>
                            <div id="detailEvaluationWordCount" style="text-align: right; font-size: 10px; color: #666; margin-top: 4px;">
                                字数：0
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="detailEvaluationRating" style="font-size: 14px; font-weight: 500; margin-bottom: 8px; display: block;">综合评价：</label>
                            <select id="detailEvaluationRating" name="rating" style="padding: 6px; border: 1px solid #ddd; border-radius: 4px; width: 100%; font-size: 13px; box-sizing: border-box;">
                                <option value="">请选择评价等级</option>
                                <option value="优秀">优秀</option>
                                <option value="良好">良好</option>
                                <option value="一般">一般</option>
                                <option value="较差">较差</option>
                            </select>
                        </div>
                        <div style="margin-top: 15px; text-align: right;">
                            <button type="submit" class="btn btn-detail" style="padding: 8px 16px; font-size: 13px;">保存评价</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 邮件发送模态框 -->
<div id="mailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">发送邮件</h2>
            <span class="close" onclick="closeMailModal()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="mailForm" onsubmit="sendMail(event)">
                <div class="form-group">
                    <label for="mailTo">收件人邮箱：</label>
                    <input type="email" id="mailTo" name="to" readonly style="background-color: #f5f5f5;">
                </div>
                <div class="form-group">
                    <label for="mailSubject">邮件主题：</label>
                    <input type="text" id="mailSubject" name="subject" value="面试通知" required
                           placeholder="请输入邮件主题..."
                           style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">

                </div>
                <div class="form-group">
                    <label for="mailContent">邮件内容：</label>
                    <div style="margin-bottom: 8px;">
                        <button type="button" onclick="loadTemplate('interview')" style="padding: 4px 8px; margin-right: 8px; font-size: 12px; background: #f8f9fa; border: 1px solid #ddd; border-radius: 3px; cursor: pointer;">面试通知模板</button>
                        <button type="button" onclick="loadTemplate('invitation')" style="padding: 4px 8px; margin-right: 8px; font-size: 12px; background: #f8f9fa; border: 1px solid #ddd; border-radius: 3px; cursor: pointer;">面试邀请模板</button>
                        <button type="button" onclick="loadTemplate('result')" style="padding: 4px 8px; font-size: 12px; background: #f8f9fa; border: 1px solid #ddd; border-radius: 3px; cursor: pointer;">面试结果模板</button>
                    </div>
                    <textarea id="mailContent" name="content" rows="12" required 
                              placeholder="请输入邮件内容，支持多行文本编辑..."
                              style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.5; resize: vertical;"
                              oninput="updateWordCount()"></textarea>
                    <div id="wordCount" style="text-align: right; font-size: 12px; color: #666; margin-top: 4px;">
                        字数：0
                    </div>

                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn" onclick="clearMailContent()" style="background: #6c757d;">清空内容</button>
            <button type="button" class="btn" onclick="closeMailModal()">取消</button>
            <button type="submit" form="mailForm" class="btn btn-detail">发送邮件</button>
        </div>
    </div>
</div>

<!-- 简历查看模态框 -->
<div id="resumeModal" class="modal">
    <div class="modal-content" style="max-width: 95%; width: 1200px; max-height: 90vh;">
        <div class="modal-header">
            <h2 class="modal-title">📄 简历查看</h2>
            <span class="close" onclick="closeResumeModal()">&times;</span>
        </div>
        <div class="modal-body" style="padding: 20px; display: flex; gap: 20px; height: calc(90vh - 120px);">
            <!-- 左侧：简历内容 -->
            <div style="flex: 1; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); display: flex; flex-direction: column;">
                <div style="padding: 20px; border-bottom: 1px solid #eee;">
                    <h3 style="margin: 0; color: #333; font-size: 16px; border-bottom: 2px solid #667eea; padding-bottom: 8px;">
                        📄 简历内容
                    </h3>
                </div>
                <div style="flex: 1; padding: 20px; overflow: hidden;">
                    <div id="resumeContent" style="height: 100%; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9; overflow: hidden;">
                        <div style="text-align: center; color: #666; padding: 50px;">
                            <div style="font-size: 48px; margin-bottom: 10px;">📄</div>
                            <div>正在加载简历内容...</div>
                        </div>
                    </div>
                </div>
                <div style="padding: 15px 20px; border-top: 1px solid #eee; text-align: center;">
                    <button class="btn btn-detail" onclick="downloadResume()" style="margin-right: 10px;">
                        <span class="btn-icon">⬇️</span>
                        下载简历
                    </button>
                    <button class="btn" onclick="closeResumeModal()">
                        <span class="btn-icon">✕</span>
                        关闭
                    </button>
                </div>
            </div>
            
            <!-- 右侧：面试评价 -->
            <div style="flex: 1; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); display: flex; flex-direction: column;">
                <div style="padding: 20px; border-bottom: 1px solid #eee;">
                    <h3 style="margin: 0; color: #333; font-size: 16px; border-bottom: 2px solid #667eea; padding-bottom: 8px;">
                        📝 面试评价
                    </h3>
                </div>
                <div style="flex: 1; padding: 20px; overflow-y: auto;">
                    <form id="resumeEvaluationForm" onsubmit="saveResumeEvaluation(event)">
                        <input type="hidden" id="resumeEvaluationAccountingId" name="accountingId">
                        <div class="form-group">
                            <label for="resumeEvaluationContent" style="font-size: 14px; font-weight: 500; margin-bottom: 8px; display: block;">评价内容：</label>
                            <textarea id="resumeEvaluationContent" name="content" rows="12" required 
                                      placeholder="请记录对面试者的评价、印象、技术能力、沟通能力等..."
                                      style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.4; resize: none; border: 1px solid #ddd; border-radius: 4px; padding: 8px; width: 100%; box-sizing: border-box; font-size: 13px;"
                                      oninput="updateResumeEvaluationWordCount()"></textarea>
                            <div id="resumeEvaluationWordCount" style="text-align: right; font-size: 10px; color: #666; margin-top: 4px;">
                                字数：0
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="resumeEvaluationRating" style="font-size: 14px; font-weight: 500; margin-bottom: 8px; display: block;">综合评价：</label>
                            <select id="resumeEvaluationRating" name="rating" style="padding: 6px; border: 1px solid #ddd; border-radius: 4px; width: 100%; font-size: 13px; box-sizing: border-box;">
                                <option value="">请选择评价等级</option>
                                <option value="优秀">优秀</option>
                                <option value="良好">良好</option>
                                <option value="一般">一般</option>
                                <option value="较差">较差</option>
                            </select>
                        </div>
                        <div style="margin-top: 15px; text-align: right;">
                            <button type="submit" class="btn btn-detail" style="padding: 8px 16px; font-size: 13px;">保存评价</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 面试评价记录模态框 -->
<div id="evaluationModal" class="modal">
    <div class="modal-content" style="max-width: 600px; width: 90%;">
        <div class="modal-header">
            <h2 class="modal-title">📝 面试评价</h2>
            <span class="close" onclick="closeEvaluationModal()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="evaluationForm" onsubmit="saveEvaluation(event)">
                <input type="hidden" id="evaluationAccountingId" name="accountingId">
                <div class="form-group">
                    <label for="evaluationContent" style="font-size: 13px; font-weight: 500; margin-bottom: 8px; display: block;">评价内容：</label>
                    <textarea id="evaluationContent" name="content" rows="10" required 
                              placeholder="请记录对面试者的评价、印象、技术能力、沟通能力等..."
                              style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.4; resize: none; border: 1px solid #ddd; border-radius: 4px; padding: 8px; width: 100%; box-sizing: border-box; font-size: 13px;"
                              oninput="updateEvaluationWordCount()"></textarea>
                    <div id="evaluationWordCount" style="text-align: right; font-size: 10px; color: #666; margin-top: 4px;">
                        字数：0
                    </div>
                </div>
                <div class="form-group">
                    <label for="evaluationRating" style="font-size: 13px; font-weight: 500; margin-bottom: 8px; display: block;">综合评价：</label>
                    <select id="evaluationRating" name="rating" style="padding: 6px; border: 1px solid #ddd; border-radius: 4px; width: 100%; font-size: 13px; box-sizing: border-box;">
                        <option value="">请选择评价等级</option>
                        <option value="优秀">优秀</option>
                        <option value="良好">良好</option>
                        <option value="一般">一般</option>
                        <option value="较差">较差</option>
                    </select>
                </div>
            </form>
        </div>
        <div class="modal-footer" style="justify-content: center;">
            <button type="button" class="btn" onclick="closeEvaluationModal()">关闭</button>
            <button type="submit" form="evaluationForm" class="btn btn-detail">保存</button>
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentPage = 1;
    let totalPages = 0;
    const pageSize = 10;

    // 页面加载事件
    window.onload = () => {
        // 默认显示面试数据，通知数据在需要时才加载
        fetchAccountingData(1);
        
        // 初始化通知数据
        fetchNotifications();
        updateNotificationBadge();
        
        // 监听来自其他页面的刷新通知
        const refreshChannel = new BroadcastChannel('dashboard-refresh');
        refreshChannel.onmessage = function(event) {
            if (event.data === 'refresh') {
                console.log('收到刷新通知，正在刷新数据...');
                // 刷新面试数据
                fetchAccountingData(1);
                // 刷新通知数据
                fetchNotifications();
                updateNotificationBadge();
                showToast('数据已自动刷新', 'info');
            }
        };
        
        // 检查是否有新通知（页面刚打开时）
        const savedNotificationCount = getLastNotificationCount();
        if (savedNotificationCount > 0) {
            // 延迟检查，确保数据加载完成
            setTimeout(() => {
                const currentCount = lastNotificationCount;
                if (currentCount > savedNotificationCount) {
                    showToast(`有 ${currentCount - savedNotificationCount} 条新通知！`, 'info');
                }
            }, 2000);
        }
        
        // 检查是否有新面试数据（页面刚打开时）
        const savedAccountingCount = getLastAccountingCount();
        if (savedAccountingCount > 0) {
            // 延迟检查，确保数据加载完成
            setTimeout(() => {
                const currentCount = lastAccountingCount;
                if (currentCount > savedAccountingCount) {
                    showToast(`有 ${currentCount - savedAccountingCount} 条新的面试申请！`, 'info');
                }
            }, 2000);
        }
        
        // 设置定时刷新（每30秒刷新一次）
        setInterval(() => {
            // 只在当前页面可见时刷新
            if (!document.hidden) {
                fetchAccountingData(currentPage);
                fetchNotifications();
                updateNotificationBadge();
            }
        }, 30000);
    };
    
    // 标签页切换功能
    function showTab(tabName) {
        // 隐藏所有标签页内容
        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach(content => content.classList.remove('active'));
        
        // 移除所有标签按钮的active类
        const tabButtons = document.querySelectorAll('.tab-button');
        tabButtons.forEach(button => button.classList.remove('active'));
        
        // 显示选中的标签页
        document.getElementById(tabName).classList.add('active');
        
        // 激活对应的标签按钮
        event.target.classList.add('active');
        
        // 如果是通知标签页，刷新通知数据
        if (tabName === 'notifications') {
            fetchNotifications();
            updateNotificationBadge();
        }
        // 如果是面试数据标签页，刷新面试数据
        else if (tabName === 'accounting') {
            fetchAccountingData(1);
        }
    }
    
    // 全局变量存储上次的通知数量
    let lastNotificationCount = 0;
    // 全局变量存储上次的面试数据数量
    let lastAccountingCount = 0;
    
    // 从localStorage获取上次的通知数量
    function getLastNotificationCount() {
        const count = localStorage.getItem('lastNotificationCount');
        return count ? parseInt(count) : 0;
    }
    
    // 保存通知数量到localStorage
    function saveNotificationCount(count) {
        localStorage.setItem('lastNotificationCount', count.toString());
    }
    
    // 从localStorage获取上次的面试数据数量
    function getLastAccountingCount() {
        const count = localStorage.getItem('lastAccountingCount');
        return count ? parseInt(count) : 0;
    }
    
    // 保存面试数据数量到localStorage
    function saveAccountingCount(count) {
        localStorage.setItem('lastAccountingCount', count.toString());
    }
    
    // 获取所有通知数据
    async function fetchNotifications() {
        try {
            const response = await fetch('/api/notifications');
            const notifications = await response.json();
            
            // 获取上次保存的通知数量
            const savedCount = getLastNotificationCount();
            
            // 检查是否有新通知
            if (notifications.length > savedCount && savedCount > 0) {
                showToast(`收到 ${notifications.length - savedCount} 条新通知！`, 'success');
            }
            
            // 更新通知数量
            lastNotificationCount = notifications.length;
            saveNotificationCount(notifications.length);
            
            // 渲染通知列表
            renderNotifications(notifications);
        } catch (error) {
            console.error('加载通知失败:', error);
        }
    }


    
    // 渲染通知列表
    function renderNotifications(notifications) {
        const notificationList = document.getElementById('notificationList');
        const notificationCount = document.getElementById('notificationCount');
        
        // 更新通知数量
        notificationCount.textContent = `共 ${notifications.length} 条通知`;
        
        if (notifications.length === 0) {
            notificationList.innerHTML = '<p style="text-align: center; color: #666;">暂无通知</p>';
            return;
        }
        
        // 未读在前，已读在后
        notifications.sort(function(a, b) {
            return (a.isRead === b.isRead) ? 0 : (a.isRead ? 1 : -1);
        });

        notificationList.innerHTML = notifications.map(notification => `
            <div class="notification-item ${notification.isRead ? 'read' : 'unread'}">
                <div class="notification-checkbox">
                    <input type="checkbox" id="notification-${notification.id}" value="${notification.id}" 
                           ${notification.isRead ? 'disabled' : ''} 
                           onchange="updateSelectedNotifications()">
                    <label for="notification-${notification.id}"></label>
                </div>
                <div class="notification-content">
                    <strong>${notification.title}</strong>
                    <p>${notification.content}</p>
                </div>
                <div class="notification-time">${formatDate(notification.createTime)}</div>
                <div class="notification-actions">
                    ${!notification.isRead ? 
                        `<button class="btn btn-mark-read" onclick="markNotificationAsRead(${notification.id})">
                            <span class="btn-icon">✓</span>
                            标记已读
                        </button>` : 
                        ''
                    }
                    <button class="btn btn-view" onclick="viewNotificationDetail(${notification.id})">
                        <span class="btn-icon">👁</span>
                      查看详情
                    </button>
                    <button class="btn btn-resume" onclick="viewNotificationResume(${notification.accountingInfoId || null})">
                        <span class="btn-icon">📄</span>
                        查看简历
                    </button>
                    <button class="btn btn-pass" onclick="markNotificationAsPassed(${notification.accountingInfoId || null}, this)">
                        <span class="btn-icon">✅</span>
                        面试通过
                    </button>
                    <button class="btn btn-mail" onclick="openNotificationMailModal(${notification.accountingInfoId || null})">
                        <span class="btn-icon">✉️</span>
                        发送邮件
                    </button>
                </div>
            </div>
        `).join('');
        syncSelectAllCheckbox();
    }
    
    // 标记通知为已读
    async function markNotificationAsRead(id) {
        try {
            const response = await fetch(`/api/notifications/${id}/read`, {
                method: 'POST'
            });
            
            if (response.ok) {
                // 重新加载通知列表
                fetchNotifications();
                // 更新通知徽章
                updateNotificationBadge();
            }
        } catch (error) {
            console.error('标记已读失败:', error);
        }
    }
    
    // 查看通知详情
    function viewNotificationDetail(id) {
        // 先获取通知信息，然后根据accountingInfoId查看详情
        fetch(`/api/notifications/${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data.accountingInfoId) {
                    openDetailModal(data.data.accountingInfoId);
                } else {
                    showToast('无法获取通知详情', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('获取通知详情失败', 'error');
            });
    }
    
    function viewNotificationResume(accountingInfoId) {
        // 检查accountingInfoId是否有效
        if (!accountingInfoId || accountingInfoId === 0) {
            showToast('无法获取面试者信息', 'error');
            return;
        }
        
        fetch(`/api/resume/${accountingInfoId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 在当前页面显示简历
                    showResumeModal(data.data);
                } else {
                    showToast('简历文件不存在', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('获取简历失败', 'error');
            });
    }
    
    // 更新通知徽章
    function updateNotificationBadge() {
        fetch('/api/notifications/unread/count')
            .then(response => response.json())
            .then(data => {
                const badge = document.getElementById('notificationBadge');
                if (data.count > 0) {
                    badge.textContent = data.count;
                    badge.style.display = 'inline';
                } else {
                    badge.style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    // 通知中心：无自动刷新，只在页面加载、手动操作、外部调用时刷新

    function getCurrentSearchDate() {
        return document.getElementById('notificationSearchDate').value;
    }

    // 搜索通知
    async function searchNotifications() {
        await fetchAndRenderNotifications();
    }

    // 清空通知搜索
    function clearNotificationSearch() {
        document.getElementById('notificationSearchDate').value = '';
        fetchAndRenderNotifications();
    }

    // 加载通知数据（未读模式/搜索模式）
    async function fetchAndRenderNotifications() {
        const searchDate = getCurrentSearchDate();
        let url = '/api/notifications/unread';
        if (searchDate) {
            url = '/api/notifications?date=' + encodeURIComponent(searchDate);
        }
        try {
            const response = await fetch(url);
            const notifications = await response.json();
            renderNotifications(notifications);
        } catch (error) {
            console.error('加载通知失败:', error);
        }
    }

    // 优化通知和面试数据的动态刷新，无论当前tab是否active
    window.fetchAndRenderNotifications = async function() {
        await fetchNotifications();
        // 如果当前tab不是通知中心，也刷新tab内容
        const notificationsTab = document.getElementById('notifications');
        if (notificationsTab && !notificationsTab.classList.contains('active')) {
            // 强制刷新tab内容（内容已被fetchNotifications更新）
            // 不切换tab，只刷新内容
        }
    };

    // 页面加载时只加载一次
    window.addEventListener('DOMContentLoaded', function() {
        fetchAndRenderNotifications();
    });



    // 全选/全不选
    function toggleSelectAll(checkbox) {
        const boxes = document.querySelectorAll('#notificationList input[type="checkbox"]:not(:disabled)');
        boxes.forEach(cb => cb.checked = checkbox.checked);
        updateSelectedNotifications();
    }

    // 复选框状态同步全选框
    function syncSelectAllCheckbox() {
        const allBoxes = document.querySelectorAll('#notificationList input[type="checkbox"]:not(:disabled)');
        const selectAll = document.getElementById('selectAll');
        if (!selectAll) return;
        if (allBoxes.length === 0) {
            selectAll.checked = false;
            selectAll.disabled = true;
        } else {
            selectAll.disabled = false;
            selectAll.checked = Array.from(allBoxes).every(cb => cb.checked);
        }
    }

    // 选中通知时同步全选框
    function updateSelectedNotifications() {
        syncSelectAllCheckbox();
    }

    // 批量标记已读
    async function markSelectedAsRead() {
        const checkboxes = document.querySelectorAll('#notificationList input[type="checkbox"]:checked:not([disabled])');
        if (checkboxes.length === 0) {
            showToast('请先选择要标记的通知', 'warning');
            return;
        }
        const notificationIds = Array.from(checkboxes).map(cb => cb.value);
        try {
            const response = await fetch('/api/notifications/batch-read', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids: notificationIds })
            });
            const result = await response.json();
            if (result.success) {
                showToast(`成功标记 ${notificationIds.length} 条通知为已读`, 'success');
                fetchAndRenderNotifications();
                updateNotificationBadge();
            } else {
                showToast('批量标记失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('批量标记失败:', error);
            showToast('批量标记失败', 'error');
        }
    }

    // 全部标记已读
    async function markAllAsRead() {
        try {
            const response = await fetch('/api/notifications/all-read', { method: 'POST' });
            const result = await response.json();
            if (result.success) {
                showToast('已将所有通知标记为已读', 'success');
                fetchAndRenderNotifications();
                updateNotificationBadge();
            } else {
                showToast('全部标记失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('全部标记失败:', error);
            showToast('全部标记失败', 'error');
        }
    }

    // 获取面试数据
    async function fetchAccountingData(page = 1) {
        currentPage = page;
        const searchName = document.getElementById('searchName').value.trim();
        const searchDate = document.getElementById('searchDate').value;
        console.log('搜索参数:', { searchName, searchDate, page });
        try {
            let url = `/api/accounting/data?page=${currentPage}&size=${pageSize}&sort=create_time,desc`;
            if (searchName) {
                url += `&name=${encodeURIComponent(searchName)}`;
            }
            if (searchDate) {
                url += `&date=${encodeURIComponent(searchDate)}`;
            }
            console.log('请求URL:', url);
            const response = await fetch(url);
            console.log('响应状态:', response.status);
            const result = await response.json();
            console.log('响应数据:', result);
            const {data, total} = result;
            const tableBody = document.querySelector('#accountingTable tbody');
            tableBody.innerHTML = '';

            // 检查是否有新面试数据
            const savedCount = getLastAccountingCount();
            if (total > savedCount && savedCount > 0) {
                showToast(`收到 ${total - savedCount} 条新的面试申请！`, 'success');
            }
            
            // 更新面试数据数量
            lastAccountingCount = total;
            saveAccountingCount(total);

            // 更新总页数
            totalPages = Math.ceil(total / pageSize);
            document.getElementById('pageInfo').textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;

            // 禁用/启用分页按钮
            document.getElementById('prevPage').disabled = currentPage <= 1;
            document.getElementById('nextPage').disabled = currentPage >= totalPages;

            if (data.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="9" style="text-align: center;">暂无数据</td>';
                tableBody.appendChild(row);
                return;
            }

            data.forEach(item => {
                // 面试状态显示对勾或按钮
                const statusHtml = item.isPassed ?
                    '<span class="status-passed">已通过</span>' :
                    `<button class="pass-button" onclick="markAsPassed(${item.id}, this)">待通过</button>`;

                // 简历按钮
                const resumeHtml = item.hasResume ? 
                    `<button class="btn btn-resume" onclick="viewResume(${item.id})">
                        <span class="btn-icon">📄</span>
                        查看简历
                    </button>` : 
                    '<span class="no-resume" style="text-align: center; display: block;">无简历</span>';

                // 面试评价按钮
                const evaluationHtml = item.evaluation ? 
                    `<button class="btn btn-evaluation" onclick="viewEvaluation(${item.id})">
                        <span class="btn-icon">📝</span>
                        查看评价
                    </button>` : 
                    `<button class="btn btn-evaluation" onclick="openEvaluationModal(${item.id})">
                        <span class="btn-icon">✏️</span>
                        添加评价
                    </button>`;

                const row = document.createElement('tr');
                row.innerHTML = `
                        <td>${item.name || ''}</td>
                        <td>${item.gender || ''}</td>
                    <td>${item.phone || ''}</td>
                        <td>${item.position || ''}</td>
                        <td>${formatDate(item.create_time) || ''}</td>
                        <td style="text-align: center;">${statusHtml}</td>
                    <td style="text-align: center;">${resumeHtml}</td>
                    <td style="text-align: center;">${evaluationHtml}</td>
                    <td style="text-align: center;">
                        <button class="btn btn-detail" onclick="openDetailModal(${item.id})">
                            <span class="btn-icon">👁</span>
                            查看详细
                        </button>
                    </td>
                    <td style="text-align: center;">
                        <button class="btn btn-mail" onclick="openMailModal('${item.email || ''}', '${item.name || ''}')">
                            <span class="btn-icon">✉️</span>
                            发送邮件
                        </button>
                    </td>
                    `;
                tableBody.appendChild(row);
            });
        } catch (error) {
            console.error('获取面试数据失败:', error);
        }
    }

    // 处理回车键搜索
    function handleKeyPress(event) {
        if (event.key === 'Enter') {
            console.log('回车键触发搜索');
            searchAccountingData();
        }
    }

    // 搜索面试数据
    function searchAccountingData() {
        console.log('执行搜索功能');
        fetchAccountingData(1);
    }



    // 清空搜索条件
    function clearSearch() {
        console.log('清空搜索条件');
        document.getElementById('searchName').value = '';
        document.getElementById('searchDate').value = '';
        fetchAccountingData(1);
    }

    // 分页切换
    function changePage(direction) {
        const newPage = currentPage + direction;
        if (newPage >= 1 && newPage <= totalPages) {
            fetchAccountingData(newPage);
        }
    }

    // 打开详细信息模态框
    async function openDetailModal(accountingId) {
        try {
            // 1. 获取用户基本信息
            const userResponse = await fetch(`/api/accounting/data/${accountingId}`);
            const userData = await userResponse.json();

            // 2. 获取用户的练习题数据
            const exercisesResponse = await fetch(`/api/exercises/data?accountingId=${accountingId}`);
            const exercisesData = await exercisesResponse.json();
            
            console.log('获取到的练习题数据:', exercisesData);

            // 3. 渲染用户信息
            renderUserInfo(userData);

            // 4. 渲染练习题数据
            renderExercises(exercisesData);

            // 5. 显示模态框
            document.getElementById('detailModal').style.display = 'block';
            
            // 6. 自动加载评价内容
            loadDetailEvaluation(accountingId);
        } catch (error) {
            console.error('获取详细数据失败:', error);
        }
    }

    // 渲染用户详细信息
    function renderUserInfo(userData) {
        const userInfoDiv = document.getElementById('userInfo');
        userInfoDiv.innerHTML = `
                <div class="form-section">
                    <h3>基本情况</h3>
                    <table class="form-table">
                        <tr>
                            <td class="form-label">填表日期:</td>
                            <td colspan="3">${userData.formDate || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">中文姓名:</td>
                            <td>${userData.name || '未填写'}</td>
                            <td class="form-label">性别:</td>
                            <td>${userData.gender || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">出生年月:</td>
                            <td>${userData.birthDate || '未填写'}</td>
                            <td class="form-label">申请职位:</td>
                            <td>${userData.position || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">学历:</td>
                            <td>${userData.education || '未填写'}</td>
                            <td class="form-label">专业:</td>
                            <td>${userData.major || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">婚姻状况:</td>
                            <td>${userData.maritalStatus || '未填写'}</td>
                            <td class="form-label">期望薪金:</td>
                            <td>${userData.expectedSalary || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">身高:</td>
                            <td>${userData.height || '未填写'}</td>
                            <td class="form-label">民族:</td>
                            <td>${userData.nationality || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">籍贯:</td>
                            <td>${userData.nativePlace || '未填写'}</td>
                            <td class="form-label">身份证号码:</td>
                            <td>${userData.idNumber || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">户口地址:</td>
                            <td colspan="3">${userData.householdAddress || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">现住地址:</td>
                            <td colspan="3">${userData.currentAddress || '未填写'}</td>
                        </tr>
                        <tr>
                            <td class="form-label">联系电话:</td>
                            <td>${userData.phone || '未填写'}</td>
                            <td class="form-label">电子邮箱:</td>
                            <td>${userData.email || '未填写'}</td>
                        </tr>
                    </table>
                </div>

                <div class="form-section">
                    <h3>工作经历</h3>
                    <table class="form-table experience-table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>单位名称</th>
                                <th>职位</th>
                                <th>离职原因</th>
                            </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td>${userData.workExperience1Time || '未填写'}</td>
                            <td>${userData.workExperience1Company || '未填写'}</td>
                            <td>${userData.workExperience1Position || '未填写'}</td>
                            <td>${userData.workExperience1Reason || '未填写'}</td>
                            </tr>
                        <tr>
                            <td>${userData.workExperience2Time || '未填写'}</td>
                            <td>${userData.workExperience2Company || '未填写'}</td>
                            <td>${userData.workExperience2Position || '未填写'}</td>
                            <td>${userData.workExperience2Reason || '未填写'}</td>
                            </tr>
                        <tr>
                            <td>${userData.workExperience3Time || '未填写'}</td>
                            <td>${userData.workExperience3Company || '未填写'}</td>
                            <td>${userData.workExperience3Position || '未填写'}</td>
                            <td>${userData.workExperience3Reason || '未填写'}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="form-section">
                <h3>教育经历</h3>
                <table class="form-table experience-table">
                        <thead>
                            <tr>
                                <th>时间</th>
                            <th>学校名称</th>
                            <th>专业</th>
                            <th>学历</th>
                            </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td>${userData.education1Time || '未填写'}</td>
                            <td>${userData.education1School || '未填写'}</td>
                            <td>${userData.education1Major || '未填写'}</td>
                            <td>${userData.education1Degree || '未填写'}</td>
                        </tr>
                        <tr>
                            <td>${userData.education2Time || '未填写'}</td>
                            <td>${userData.education2School || '未填写'}</td>
                            <td>${userData.education2Major || '未填写'}</td>
                            <td>${userData.education2Degree || '未填写'}</td>
                        </tr>
                    </tbody>
                    </table>
                </div>
            `;
    }

    // 渲染练习题数据
    function renderExercises(exercisesData) {
        const exercisesTable = document.getElementById('exercisesTable');
        const tbody = exercisesTable.querySelector('tbody');
        tbody.innerHTML = '';

        if (exercisesData && exercisesData.length > 0) {
            exercisesData.forEach(exercise => {
                // 添加三道题的答案
                const questions = [
                    { title: '1. 斐波那契数列', answer: exercise.q1 },
                    { title: '2. 解析字符', answer: exercise.q2 },
                    { title: '3. 数组去重', answer: exercise.q3 }
                ];
                
                questions.forEach(q => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${q.title}</td>
                        <td>${q.answer || '未填写'}</td>
                    `;
                    tbody.appendChild(row);
                });
            });
        } else {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="2" style="text-align: center;">暂无练习题数据</td>';
            tbody.appendChild(row);
        }
    }

    // 查看简历
    function viewResume(accountingId) {
        fetch(`/api/resume/${accountingId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 在当前页面显示简历
                    showResumeModal(data.data);
                } else {
                    showToast('简历文件不存在', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('获取简历失败', 'error');
            });
    }

    // 标记为通过
    async function markAsPassed(id, button) {
        try {
            const response = await fetch(`/api/accounting/markPassed/${id}`, {
                method: 'POST'
            });
            
            if (response.ok) {
                // 替换按钮为已通过状态
                const statusCell = button.parentElement;
                statusCell.innerHTML = '<span class="status-passed">已通过</span>';
                
                // 显示成功提示
                showToast('面试状态已更新为通过', 'success');
            } else {
                showToast('更新失败，请重试', 'error');
            }
        } catch (error) {
            console.error('标记通过失败:', error);
            showToast('网络错误，请重试', 'error');
        }
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    // 移除自动刷新相关代码
    // 删除 startAutoRefresh 函数定义及调用
    // 删除 setInterval、window.addEventListener('focus', ...)、document.addEventListener('visibilitychange', ...)

    // 显示提示消息
    function showToast(message, type = 'info') {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 显示动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 100);
        
        // 3秒后自动移除
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 3000);
    }

    // 模态框关闭事件
    document.addEventListener('DOMContentLoaded', function() {
        const modal = document.getElementById('detailModal');
        const closeBtn = modal.querySelector('.close');
        
        closeBtn.onclick = function() {
            modal.style.display = 'none';
        }
        
        window.onclick = function(event) {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        }
        
        // 邮件模态框关闭事件
        const mailModal = document.getElementById('mailModal');
        const mailCloseBtn = mailModal.querySelector('.close');
        
        mailCloseBtn.onclick = function() {
            mailModal.style.display = 'none';
        }
        
        window.onclick = function(event) {
            if (event.target === mailModal) {
                mailModal.style.display = 'none';
            }
            if (event.target === evaluationModal) {
                evaluationModal.style.display = 'none';
            }
        }
    });

    // 打开邮件发送模态框
    function openMailModal(email, name) {
        if (!email) {
            showToast('该用户没有填写邮箱地址', 'warning');
            return;
        }
        
                                document.getElementById('mailTo').value = email;
        document.getElementById('mailSubject').value = '面试通知';
        // 提供可编辑的默认模板，用户可以自由修改
        document.getElementById('mailContent').value = `您好${name ? '，' + name : ''}：

感谢您参加我们的面试。

此邮件为面试相关通知，请查收。

如有任何问题，请随时联系我们。

祝好！
面试官`;
        document.getElementById('mailModal').style.display = 'block';
        updateWordCount();
    }

    // 关闭邮件发送模态框
    function closeMailModal() {
        document.getElementById('mailModal').style.display = 'none';
    }

    // 清空邮件内容
    function clearMailContent() {
        if (confirm('确定要清空邮件内容吗？')) {
            document.getElementById('mailSubject').value = '';
            document.getElementById('mailContent').value = '';
            updateWordCount();
            showToast('邮件内容已清空', 'info');
        }
    }

    // 更新字数统计
    function updateWordCount() {
        const content = document.getElementById('mailContent').value;
        const wordCount = content.length;
        document.getElementById('wordCount').textContent = `字数：${wordCount}`;
    }

    // 更新评价字数统计
    function updateEvaluationWordCount() {
        const content = document.getElementById('evaluationContent').value;
        const wordCount = content.length;
        document.getElementById('evaluationWordCount').textContent = `字数：${wordCount}`;
    }

    // 打开评价模态框
    async function openEvaluationModal(accountingId) {
        document.getElementById('evaluationAccountingId').value = accountingId;
        
        try {
            // 尝试加载已有的评价内容
            const response = await fetch(`/api/evaluation/${accountingId}`);
            const result = await response.json();
            
            if (result.success && result.data) {
                // 如果有已保存的评价，加载到表单中
                document.getElementById('evaluationContent').value = result.data.content || '';
                document.getElementById('evaluationRating').value = result.data.rating || '';
            } else {
                // 如果没有评价，清空表单
                document.getElementById('evaluationContent').value = '';
                document.getElementById('evaluationRating').value = '';
            }
        } catch (error) {
            // 如果加载失败，清空表单
            document.getElementById('evaluationContent').value = '';
            document.getElementById('evaluationRating').value = '';
        }
        
        updateEvaluationWordCount();
        document.getElementById('evaluationModal').style.display = 'block';
    }

    // 关闭评价模态框
    function closeEvaluationModal() {
        document.getElementById('evaluationModal').style.display = 'none';
    }

    // 保存评价
    async function saveEvaluation(event) {
        event.preventDefault();
        
        const accountingId = document.getElementById('evaluationAccountingId').value;
        const content = document.getElementById('evaluationContent').value;
        const rating = document.getElementById('evaluationRating').value;
        
        if (!content.trim()) {
            showToast('请填写评价内容', 'warning');
            return;
        }
        
        try {
            const response = await fetch('/api/evaluation/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    accountingId: accountingId,
                    content: content,
                    rating: rating
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                showToast('评价保存成功！', 'success');
                // 不关闭评价窗口，让用户可以继续编辑
                // 刷新面试数据以更新评价按钮状态
                fetchAccountingData(currentPage);
            } else {
                showToast('评价保存失败: ' + (result.message || '未知错误'), 'error');
            }
        } catch (error) {
            console.error('保存评价失败:', error);
            showToast('网络错误，请重试', 'error');
        }
    }

    // 查看评价
    async function viewEvaluation(accountingId) {
        try {
            const response = await fetch(`/api/evaluation/${accountingId}`);
            const result = await response.json();
            
            if (result.success && result.data) {
                const evaluation = result.data;
                document.getElementById('evaluationAccountingId').value = accountingId;
                document.getElementById('evaluationContent').value = evaluation.content || '';
                document.getElementById('evaluationRating').value = evaluation.rating || '';
                updateEvaluationWordCount();
                document.getElementById('evaluationModal').style.display = 'block';
            } else {
                showToast('无法获取评价信息', 'error');
            }
        } catch (error) {
            console.error('获取评价失败:', error);
            showToast('网络错误，请重试', 'error');
        }
    }

    // 显示简历模态框
    function showResumeModal(resumeData) {
        // 设置当前简历ID，用于下载功能
        window.currentResumeId = resumeData.id;
        
        document.getElementById('resumeModal').style.display = 'block';
        
        // 加载简历内容
        loadResumeContent(resumeData.id);
        
        // 自动加载评价内容
        loadResumeEvaluation(resumeData.accountingInfoId);
    }

    // 关闭简历模态框
    function closeResumeModal() {
        document.getElementById('resumeModal').style.display = 'none';
    }

    // 加载简历内容
    async function loadResumeContent(resumeId) {
        try {
            const response = await fetch(`/api/resume/content/${resumeId}`);
            const result = await response.json();
            
            if (result.success) {
                const data = result.data;
                const resumeContent = document.getElementById('resumeContent');
                
                if (data.isPdf) {
                    // 对于PDF文件，使用iframe显示
                    resumeContent.innerHTML = `
                        <div style="width: 100%; height: 500px; border: 1px solid #ddd; border-radius: 4px;">
                            <iframe 
                                src="data:application/pdf;base64,${data.content}" 
                                width="100%" 
                                height="100%" 
                                style="border: none; border-radius: 4px;"
                                title="简历预览">
                            </iframe>
                        </div>
                    `;
                } else {
                    // 对于文本文件，直接显示内容
                    resumeContent.innerHTML = `
                        <div style="background: white; padding: 15px; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 13px; line-height: 1.6; white-space: pre-wrap; overflow-y: auto; max-height: 500px; border: 1px solid #ddd;">
                            ${data.content || '简历内容为空'}
                        </div>
                    `;
                }
            } else {
                document.getElementById('resumeContent').innerHTML = `
                    <div style="text-align: center; color: #666; padding: 50px;">
                        <div style="font-size: 48px; margin-bottom: 10px;">❌</div>
                        <div>无法加载简历内容</div>
                        <div style="font-size: 12px; margin-top: 10px;">${result.message || '未知错误'}</div>
                    </div>
                `;
            }
        } catch (error) {
            console.error('加载简历内容失败:', error);
            document.getElementById('resumeContent').innerHTML = `
                <div style="text-align: center; color: #666; padding: 50px;">
                    <div style="font-size: 48px; margin-bottom: 10px;">❌</div>
                    <div>网络错误，请重试</div>
                </div>
            `;
        }
    }

    // 下载简历
    function downloadResume() {
        const resumeId = window.currentResumeId;
        if (resumeId) {
            window.open(`/api/resume/download/${resumeId}`, '_blank');
        } else {
            showToast('无法获取简历ID', 'error');
        }
    }

    // 加载简历评价内容
    async function loadResumeEvaluation(accountingId) {
        document.getElementById('resumeEvaluationAccountingId').value = accountingId;
        
        try {
            const response = await fetch(`/api/evaluation/${accountingId}`);
            const result = await response.json();
            
            if (result.success && result.data) {
                document.getElementById('resumeEvaluationContent').value = result.data.content || '';
                document.getElementById('resumeEvaluationRating').value = result.data.rating || '';
            } else {
                document.getElementById('resumeEvaluationContent').value = '';
                document.getElementById('resumeEvaluationRating').value = '';
            }
        } catch (error) {
            document.getElementById('resumeEvaluationContent').value = '';
            document.getElementById('resumeEvaluationRating').value = '';
        }
        
        updateResumeEvaluationWordCount();
    }

    // 更新简历评价字数统计
    function updateResumeEvaluationWordCount() {
        const content = document.getElementById('resumeEvaluationContent').value;
        const wordCount = content.length;
        document.getElementById('resumeEvaluationWordCount').textContent = `字数：${wordCount}`;
    }

    // 保存简历评价
    async function saveResumeEvaluation(event) {
        event.preventDefault();
        
        const accountingId = document.getElementById('resumeEvaluationAccountingId').value;
        const content = document.getElementById('resumeEvaluationContent').value;
        const rating = document.getElementById('resumeEvaluationRating').value;
        
        if (!content.trim()) {
            showToast('请填写评价内容', 'warning');
            return;
        }
        
        try {
            const response = await fetch('/api/evaluation/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    accountingId: accountingId,
                    content: content,
                    rating: rating
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                showToast('评价保存成功！', 'success');
                // 刷新面试数据以更新评价按钮状态
                fetchAccountingData(currentPage);
            } else {
                showToast('评价保存失败: ' + (result.message || '未知错误'), 'error');
            }
        } catch (error) {
            console.error('保存评价失败:', error);
            showToast('网络错误，请重试', 'error');
        }
    }

    // 加载详细信息评价内容
    async function loadDetailEvaluation(accountingId) {
        document.getElementById('detailEvaluationAccountingId').value = accountingId;
        
        try {
            const response = await fetch(`/api/evaluation/${accountingId}`);
            const result = await response.json();
            
            if (result.success && result.data) {
                document.getElementById('detailEvaluationContent').value = result.data.content || '';
                document.getElementById('detailEvaluationRating').value = result.data.rating || '';
            } else {
                document.getElementById('detailEvaluationContent').value = '';
                document.getElementById('detailEvaluationRating').value = '';
            }
        } catch (error) {
            document.getElementById('detailEvaluationContent').value = '';
            document.getElementById('detailEvaluationRating').value = '';
        }
        
        updateDetailEvaluationWordCount();
    }

    // 更新详细信息评价字数统计
    function updateDetailEvaluationWordCount() {
        const content = document.getElementById('detailEvaluationContent').value;
        const wordCount = content.length;
        document.getElementById('detailEvaluationWordCount').textContent = `字数：${wordCount}`;
    }

    // 保存详细信息评价
    async function saveDetailEvaluation(event) {
        event.preventDefault();
        
        const accountingId = document.getElementById('detailEvaluationAccountingId').value;
        const content = document.getElementById('detailEvaluationContent').value;
        const rating = document.getElementById('detailEvaluationRating').value;
        
        if (!content.trim()) {
            showToast('请填写评价内容', 'warning');
            return;
        }
        
        try {
            const response = await fetch('/api/evaluation/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    accountingId: accountingId,
                    content: content,
                    rating: rating
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                showToast('评价保存成功！', 'success');
                // 刷新面试数据以更新评价按钮状态
                fetchAccountingData(currentPage);
            } else {
                showToast('评价保存失败: ' + (result.message || '未知错误'), 'error');
            }
        } catch (error) {
            console.error('保存评价失败:', error);
            showToast('网络错误，请重试', 'error');
        }
    }



    // 发送邮件
    async function sendMail(event) {
        event.preventDefault();
        
        const to = document.getElementById('mailTo').value;
        const subject = document.getElementById('mailSubject').value;
        const content = document.getElementById('mailContent').value;
        
        console.log('发送邮件参数:', { to, subject, content });
        
        if (!to || !subject || !content) {
            showToast('请填写完整的邮件信息', 'warning');
            return;
        }
        
        try {
            const requestBody = {
                to: to,
                subject: subject,
                content: content
            };
            
            console.log('发送邮件请求体:', requestBody);
            
            const response = await fetch('/api/sendMail', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            });
            
            console.log('邮件发送响应状态:', response.status);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            console.log('邮件发送响应结果:', result);
            
            if (result.success) {
                showToast('邮件发送成功！', 'success');
                closeMailModal();
            } else {
                showToast('邮件发送失败: ' + (result.message || '未知错误'), 'error');
            }
        } catch (error) {
            console.error('发送邮件失败:', error);
            showToast('网络错误，请重试', 'error');
        }
    }

    window.fetchAndRenderAccountingData = function() {
        fetchAccountingData(1);
    };

    // 通知中的面试通过功能
    async function markNotificationAsPassed(accountingInfoId, button) {
        // 检查accountingInfoId是否有效
        if (!accountingInfoId || accountingInfoId === 0) {
            showToast('无法获取面试者信息', 'error');
            return;
        }
        
        try {
            const response = await fetch(`/api/accounting/markPassed/${accountingInfoId}`, {
                method: 'POST'
            });
            
            if (response.ok) {
                // 更新按钮状态
                button.innerHTML = '<span class="btn-icon">✅</span>已通过';
                button.disabled = true;
                button.style.backgroundColor = '#28a745';
                showToast('面试状态已更新为通过', 'success');
                
                // 刷新面试数据
                fetchAccountingData(currentPage);
            } else {
                showToast('更新失败，请重试', 'error');
            }
        } catch (error) {
            console.error('更新面试状态失败:', error);
            showToast('网络错误，请重试', 'error');
        }
    }

    // 通知中的发送邮件功能
    async function openNotificationMailModal(accountingInfoId) {
        console.log('openNotificationMailModal called with accountingInfoId:', accountingInfoId);
        
        // 检查accountingInfoId是否有效
        if (!accountingInfoId || accountingInfoId === 0) {
            showToast('无法获取面试者信息', 'error');
            return;
        }
        
        try {
            // 先获取面试者信息
            const url = `/api/accounting/data/${accountingInfoId}`;
            console.log('Fetching from URL:', url);
            
            const response = await fetch(url);
            console.log('Response status:', response.status);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const accountingInfo = await response.json();
            console.log('Received accountingInfo:', accountingInfo);
            
            if (accountingInfo) {
                const email = accountingInfo.email;
                const name = accountingInfo.name;
                
                console.log('Email:', email, 'Name:', name);
                
                if (!email) {
                    showToast('该用户没有填写邮箱地址', 'warning');
                    return;
                }
                
                document.getElementById('mailTo').value = email;
                document.getElementById('mailSubject').value = '面试通知';
                // 提供可编辑的默认模板，用户可以自由修改
                document.getElementById('mailContent').value = `您好${name ? '，' + name : ''}：

感谢您参加我们的面试。

此邮件为面试相关通知，请查收。

如有任何问题，请随时联系我们。

祝好！
面试官`;
                document.getElementById('mailModal').style.display = 'block';
            } else {
                showToast('无法获取面试者信息', 'error');
            }
        } catch (error) {
            console.error('获取面试者信息失败:', error);
            showToast('无法获取面试者信息，请检查网络连接', 'error');
        }
    }

    // 加载邮件模板
    function loadTemplate(templateType) {
        const name = document.getElementById('mailTo').value ? '，' + (document.getElementById('mailTo').value.split('@')[0] || '') : '';
        
        let subject = '';
        let content = '';
        
        switch (templateType) {
            case 'interview':
                subject = '面试通知';
                content = `您好${name}：

感谢您对我们公司的关注。

我们已收到您的面试申请，现通知您面试安排如下：

面试时间：[请填写具体时间]
面试地点：[请填写具体地点]
面试形式：[现场面试/视频面试]

请提前准备以下材料：
1. 身份证原件
2. 学历证书复印件
3. 个人简历
4. 相关证书复印件

如有任何疑问，请及时联系我们。

祝好！
面试官`;
                break;
                
            case 'invitation':
                subject = '面试邀请';
                content = `您好${name}：

恭喜您通过简历筛选！

我们诚挚地邀请您参加面试，具体安排如下：

面试时间：[请填写具体时间]
面试地点：[请填写具体地点]
面试形式：[现场面试/视频面试]

面试流程：
1. 自我介绍
2. 技术问答
3. 项目经验分享
4. 问答环节

请提前15分钟到达面试地点，并携带相关材料。

期待您的到来！

祝好！
面试官`;
                break;
                
            case 'result':
                subject = '面试结果通知';
                content = `您好${name}：

感谢您参加我们的面试。

经过综合评估，我们很高兴地通知您，您已通过面试！

后续安排：
1. 我们将尽快与您联系，安排入职事宜
2. 请准备入职所需材料
3. 具体入职时间将另行通知

如有任何疑问，请随时联系我们。

恭喜您！

祝好！
面试官`;
                break;
        }
        
        document.getElementById('mailSubject').value = subject;
        document.getElementById('mailContent').value = content;
        updateWordCount();
        
        showToast(`已加载${subject}模板，您可以自由编辑内容`, 'success');
    }
</script>
</body>
</html>